package com.yupi.springbootinit.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.springbootinit.common.BaseResponse;
import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.common.ResultUtils;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;

import com.yupi.springbootinit.mapper.CommentRqMapper;
import com.yupi.springbootinit.model.dto.commentrq.CommentRqAddRequest;
import com.yupi.springbootinit.model.dto.commentrq.CommentRqDelRequest;
import com.yupi.springbootinit.model.dto.commentrq.CommentRqParentResponse;
import com.yupi.springbootinit.model.entity.Comment;
import com.yupi.springbootinit.model.entity.CommentRq;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.service.CommentRqService;
import com.yupi.springbootinit.service.CommentService;
import com.yupi.springbootinit.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/commentrq")
@Slf4j
public class CommentRqController {

    @Resource
    private CommentRqService commentRqService;

    @Resource
    private UserService userService;

    @Resource
    private CommentRqMapper commentRqMapper;

    @PostMapping("/addCommentRq")
    public BaseResponse<Long> addCommentRq(@RequestParam(value = "commentId") Long commentId, @RequestParam(value = "parentId") Long parentId, @RequestParam(value = "content") String content, @RequestParam(value = "postId") Long postId, @RequestParam(value = "anon", defaultValue = "0") Integer anon, @RequestParam(required = false, value = "files") List<MultipartFile> files, HttpServletRequest request) {

        CommentRq commentrq = new CommentRq();
        commentrq.setCommentId(commentId);
        commentrq.setParentId(parentId);
        commentrq.setContent(content);
        commentrq.setPostId(postId);
        commentrq.setAnon(anon);

        commentRqService.validCommentRq(commentrq, true);//add为true表示参不能为空

        User loginUser = userService.getLoginUser(request);
        if(loginUser.getIsAuth()==0){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"请先实名认证再发帖哦~");
        }
        if (loginUser.getUserPoints()<=0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"积分不足");
        }

        commentrq.setUserId(loginUser.getId());
        if (commentrq.getAnon() == 1) {
            commentrq.setAnon_name(loginUser.getAnon_name());
        }

        if (files != null) {
            List<String> imgpath = commentRqService.uploadImage(files);

            commentrq.setImgpath(JSONUtil.toJsonStr(imgpath));
        }
        boolean result = commentRqService.save(commentrq);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        boolean reduceOnePoint = userService.reduceOnePoint(loginUser);
        ThrowUtils.throwIf(!reduceOnePoint,ErrorCode.SYSTEM_ERROR);
        long newCommetId = commentrq.getId();
        return ResultUtils.success(newCommetId);
    }

    @PostMapping("/deleteCommentRq")
    public BaseResponse<Boolean> deleteCommentRq(@RequestBody CommentRqDelRequest commentRqDelRequest, HttpServletRequest request) {
        if (commentRqDelRequest == null || commentRqDelRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = commentRqDelRequest.getId();
        // 判断是否存在
        CommentRq oldComment = commentRqService.getById(id);
        ThrowUtils.throwIf(oldComment == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldComment.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = commentRqService.removeById(id);
        return ResultUtils.success(b);
    }

    @GetMapping("/getCommentRqByLoginUser")
    public BaseResponse<List<CommentRq>> getCommentRqByLoginUser(HttpServletRequest request) {
        QueryWrapper<CommentRq> queryWrapper = new QueryWrapper<>();
        User user = userService.getLoginUser(request);
        Long userId = user.getId();
        queryWrapper.eq("userId", userId);
        queryWrapper.eq("isDelete", "0");
        queryWrapper.orderByDesc("createTime");
        List<CommentRq> commentRqList = commentRqMapper.selectList(queryWrapper);
        return ResultUtils.success(commentRqList);
    }

    @GetMapping("/getUserNameByParentId")
    public BaseResponse<CommentRqParentResponse> getUserNameByParentId(@RequestParam int parentId) {
        QueryWrapper<CommentRq> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", parentId);
        queryWrapper.eq("isDelete", "0");
        CommentRq commentRq = commentRqMapper.selectOne(queryWrapper);
        if (commentRq == null) {
            return ResultUtils.error(ErrorCode.NOT_FOUND_ERROR);
        }
        Long userId = commentRq.getUserId();
        User user = userService.getById(userId);
        CommentRqParentResponse commentRqParentResponse = new CommentRqParentResponse();
        commentRqParentResponse.setUserName(user.getUserName());
        commentRqParentResponse.setAnon_name(commentRq.getAnon_name());
        return ResultUtils.success(commentRqParentResponse);
    }
}
